package com.tbvtc.agriculturalcreditchainserver2025.comment.AOP;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Aspect //当前类为切面类
@Slf4j
public class RecordTimeAspect {

    @Around("execution(* com.tbvtc.agriculturalcreditchainserver2025.service.impl.*.*(..))")
    public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
        //记录方法执行开始时间
        long begin = System.currentTimeMillis();
        //执行原始方法
        Object result = pjp.proceed(); //执行原始方法
        //记录方法执行结束时间
        long end = System.currentTimeMillis();
        //计算方法执行耗时
        log.info("方法执行耗时：{}", end - begin);
        return result;
    }
   //  通过 @Around 注解为方法添加事务
    @Around("execution(* com.tbvtc.agriculturalcreditchainserver2025.service.impl.*.*(..))")
    @Transactional(rollbackFor = Exception.class) // 默认事务配置
    public Object aroundServiceMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            return joinPoint.proceed(); // 执行目标方法
        } catch (Exception e) {
            throw e; // 触发事务回滚
        }
    }
}